<?php

namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;

/**
 * 计算当日年级出勤率：php think CalculateAttendance
 */
class CalculateAttendance extends Command
{
    protected $description = '计算当日年级出勤率';

    protected function startPrint()
    {
        echo '-------------------------------------------------------------------------------' . PHP_EOL;
        echo '【当日年级出勤率计算开始' . date('Y-m-d H:i:s', time()) . '】【start】' . $this->description . PHP_EOL;
    }

    protected function endPrint()
    {
        echo '当日年级出勤率计算完毕！'. date('Y-m-d H:i:s', time()) . '】【end】' . PHP_EOL;
    }

    protected function configure()
    {
        $this->setName('CalculateAttendance')
            ->addOption('date', 'd', Option::VALUE_REQUIRED, 'date: 指定计算日期,例：20240720')
            ->setDescription($this->description);
    }

    protected function execute(Input $input, Output $output)
    {
        $this->startPrint();
        $date = $input->getOption('date') ?: '';

        // 年级信息
        $list = db('grade')
            ->field('id,schoole_id')
            ->where('mark', 1)
            ->select();
        $data = [];
        foreach ($list as $item){
            $student_count = db('student')
                ->where(['grade_id'=> $item['id'], 'status'=> 1])
                ->count('id');
            $attendance_count = db('student_work_log')
                ->where(function ($query) use($date){
                    if($date){
                        $query->where('day', $date)->whereNotNull('school_arrive_time');
                    }else{
                        $query->whereTime('school_arrive_time', 'd');
                    }
                })
                ->count('id');
            $attendance = $attendance_count ? round($attendance_count / $student_count, 2) : '0.00';
            if(!db('grade_attendance')->where(['schoole_id'=> $item['schoole_id'], 'grade_id'=> $item['id']], ['day'=> $date ?: date('Ymd')])->value('id')){
                $data[] = [
                    'schoole_id'=> $item['schoole_id'],
                    'grade_id'=> $item['id'],
                    'attendance'=> $attendance,
                    'day'=> $date ?: date('Ymd'),
                    'week'=> $date ? date('W', strtotime($date)) : date('W'),
                    'month'=> $date ? date('Ym', strtotime($date)) : date('Ym'),
                    'year'=> $date ? date('Y', strtotime($date)) : date('Y'),
                    'belong_time'=> $date ? strtotime(date('Y-m-d', strtotime($date)).' 23:59:59') : strtotime(date('Y-m-d').' 23:59:59'),
                    'create_time'=> time()
                ];
            }
        }

        if(empty($data)){
            echo '暂无需要处理的数据'. PHP_EOL;
        }

        if(!empty($data)){
            db('grade_attendance')->insertAll($data);
        }

        $this->endPrint();
    }
}